<template>
    <div>
        <van-sticky>
            <div class="head">
                <img class="head-back-img" @click="goBack" src="../../assets/back.svg" alt="">
                <div class="title">兑换</div>
            </div>
        </van-sticky>
        <div class="film_top">
            <div class="cinema_name">{{ film_Info.cinema_name }}</div>
            <div class="address">{{ film_Info.address }}</div>
        </div>
        <div class="blur-background"
            :style="{ backgroundImage: `url(${$buildFullImageUrl + (select_film.pic || '')})` }"></div>
        <div class="film_Container-wrapper">
            <!-- 新增模糊背景层 -->
            <div class="blur-bg" :style="{ backgroundImage: `url(${$buildFullImageUrl + (select_film.pic || '')})` }">
            </div>

            <div class="film_Container">
                <div class="swipe-container" v-for="(item, index) in selectTimeFilms" :key="index"
                    :ref="'filmItem_' + index" :class="{ 'active': activeIndex === index }"
                    @click="handleFilmClick(item, index)">
                    <div class="card-img">
                        <img :src="$buildFullImageUrl + item.pic" class="poster">
                    </div>
                </div>
            </div>
        </div>
        <div class="film-info-container" v-if="select_film.film_name">
            <div class="select_film_info">
                <div class="film_info_top">
                    <div class="film_name"> {{ select_film.film_name }}</div>
                    <div class="score" v-if="select_film.score">{{ select_film.score }}分</div>
                </div>
                <div class="film_info_bottom">
                    <div v-if="select_film.duration">{{ select_film.duration }}分钟</div>
                    <div class="type">{{ getFirstType(select_film.film_type) }}</div>
                    <div>{{ getFirstThreeCasts(select_film.cast) }}</div>
                </div>
            </div>
        </div>
        <van-divider :margin="12" />
        <div>
            <van-tabs v-model="activeTab" animated class="selectdate" @click="handleTabClick">
                <van-tab v-for="(date, index) in dateList" :key="index">
                    <template #title>
                        <div class="custom-tab">
                            <div class="date-name">{{ date.dateName }}</div>
                            <div class="date-value">{{ date.dateValue }}</div>
                        </div>
                    </template>
                </van-tab>
            </van-tabs>
        </div>
        <div class="movieContent">
            <!-- @load="getData" v-model="loading"-->
            <van-list :finished="finished" finished-text="没有更多数据了" class="movie-list">
                <van-cell v-for="(item, index) in selectedTimeData" :key="index" class="movie-card">
                    <div class="timeDatas">
                        <div>
                            <div>{{ item.show_time.split(' ')[1].substring(0, 5) }}</div>
                            <div>{{ item.close_time.split(' ')[1].substring(0, 5) }}</div>
                        </div>
                        <div class="middle-content">
                            <div class="text-ellipsis">{{ item.version_type }}</div>
                            <div class="text-ellipsis">{{ item.hall_name }}</div>
                        </div>
                        <div>￥{{ item.net_price }} 起</div>
                        <div @click="buyOrders(item.show_id)">
                            兑换
                        </div>
                    </div>
                </van-cell>
            </van-list>
        </div>
    </div>
</template>

<script>
import plantAPI from "@/api/plant";
export default {
    data() {
        return {
            loading: false,
            finished: false,
            page: 1,
            // 可以选择某个时间点得电影
            selectedTimeData: [],
            activeIndex: 0, // 默认选中第一个
            cardWidth: 78,
            gap: 6,
            selectTimeFilms: [],
            dateList: [],
            activeTab: 0,
            film_Info: {},
            select_film: {},

            showFilms: [],//所有排期
            uniqueFilms: []//去重得排期
        }
    },
    created() {
        // 影院信息
        this.film_Info = JSON.parse(this.$route.query.film_Info);
        // 获取路由参数中的日期和影片ID
        const selected_date = this.$route.query.selected_date;
        const fims_id = this.$route.query.fims_id;
        this.generateDateList();

        // 初始化日期选择
        if (selected_date) {
            // 查找对应的tab索引
            const dateTabIndex = this.dateList.findIndex(date => date.fullDateValue === selected_date);
            if (dateTabIndex !== -1) {
                this.activeTab = dateTabIndex;

            }
        }
        // 影院排期
        plantAPI.getshowAPI(this.film_Info.cinema_id).then(res => {
            this.showFilms = JSON.parse(res.data.body).data;
            if (this.showFilms.length == 0) {
                this.select_film = {}
                return
            }
            this.uniqueFilms = this.showFilms.filter((film, index, self) =>
                index === self.findIndex(f => f.film_id === film.film_id)
            );

            // 加载影片数据
            plantAPI.gethotAPI().then(res => {
                let records = JSON.parse(res.data.body).data.records;
                this.uniqueFilms.forEach(element => {
                    records.forEach(items => {
                        if (element.film_id == items.film_id) {
                            element.pic = items.pic;
                            element.score = items.score;
                            element.cast = items.cast;
                        }
                    });
                });

                this.selectTimeFilms = this.uniqueFilms;

                // 初始化选中的影片
                if (fims_id && this.selectTimeFilms.length > 0) {
                    const filmIndex = this.selectTimeFilms.findIndex(film => film.film_id == fims_id);
                    if (filmIndex !== -1) {
                        this.select_film = this.selectTimeFilms[filmIndex];
                        this.activeIndex = filmIndex;
                    }
                } else if (this.selectTimeFilms.length > 0) {
                    this.select_film = this.selectTimeFilms[0];
                    this.activeIndex = 0;
                }

                // 加载排片数据
                const loadDate = selected_date || this.dateList[this.activeTab].fullDateValue;
                this.selectedTimeData = this.showFilms.filter(
                    item => item.film_id == this.select_film?.film_id && item.show_date == loadDate
                );

                this.$nextTick(() => {
                    this.scrollToActiveFilm();
                });
            });
        });
    },
    methods: {
        goBack() {
            this.$router.go(-1)
        },
        buyOrders(show_id) {
            this.$router.push({
                path: '/seat',
                query: {
                    show_id,
                    cinema_id: this.film_Info.cinema_id
                }
            })
        },
        loadFilmData(date) {
            plantAPI.gethotAPI().then(res => {
                let records = JSON.parse(res.data.body).data.records;
                this.uniqueFilms.forEach(element => {
                    records.forEach(items => {
                        if (element.film_id == items.film_id) {
                            element.pic = items.pic;
                            element.score = items.score;
                            element.cast = items.cast;
                        }
                    });
                });

                this.selectTimeFilms = this.uniqueFilms;
                // 电影院排期
                if (this.selectTimeFilms.length > 0) {
                    this.select_film = this.selectTimeFilms[0];
                    this.activeIndex = 0;
                    this.selectedTimeData = this.showFilms.filter(
                        item => item.film_id == this.select_film.film_id && item.show_date == date
                    );
                    this.$nextTick(() => {
                        this.scrollToActiveFilm();
                    });
                } else {
                    this.selectedTimeData = [];
                }
            });
        },
        // 修改handleTabClick方法
        handleTabClick() {
            const selectedDate = this.dateList[this.activeTab].fullDateValue;
            // 保持当前选中的影片不变，只根据新时间查询
            if (this.select_film && this.select_film.film_id) {
                this.selectedTimeData = this.showFilms.filter(
                    item => item.film_id == this.select_film.film_id && item.show_date == selectedDate
                );
            }
        },
        // 确保DOM完全渲染后执行
        scrollToActiveFilm() {
            this.$nextTick(() => {
                const container = this.$el.querySelector('.film_Container');
                const activeItem = this.$refs[`filmItem_${this.activeIndex}`]?.[0];

                if (container && activeItem) {
                    const containerRect = container.getBoundingClientRect();
                    const itemRect = activeItem.getBoundingClientRect();

                    // 计算居中滚动位置（考虑容器边界）
                    const scrollTo = activeItem.offsetLeft - (containerRect.width / 2) + (itemRect.width / 2);

                    // 边界保护：确保不滚动过头
                    const maxScroll = container.scrollWidth - containerRect.width;
                    const clampedScroll = Math.max(0, Math.min(scrollTo, maxScroll));

                    container.scrollTo({
                        left: clampedScroll,
                        behavior: 'smooth'
                    });
                }
            });
        },

        handleFilmClick(item, index) {
            this.select_film = item;
            this.activeIndex = index;

            // 重置为当天日期
            const today = new Date();
            const fullDateValue = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

            // 查找对应的tab索引
            const todayTabIndex = this.dateList.findIndex(date => date.fullDateValue === fullDateValue);
            if (todayTabIndex !== -1) {
                this.activeTab = todayTabIndex;
            }

            // 加载当天数据
            this.selectedTimeData = this.showFilms.filter(
                film => film.film_id == this.select_film.film_id && film.show_date == fullDateValue
            );
            this.scrollToActiveFilm();
        },
        getFirstType(typeString) {
            if (!typeString) return '';
            // 分割字符串并取第一个
            const types = typeString.split(',');
            return types[0].trim();
        },

        getFirstThreeCasts(castString) {
            if (!castString) return '';
            // 分割字符串并取前三个
            const casts = castString.split(',');
            return casts.slice(0, 3).join(',').trim();
        },
        generateDateList() {
            const dateList = [];
            const today = new Date();
            const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

            for (let i = 0; i < 6; i++) {
                const currentDate = new Date(today);
                currentDate.setDate(today.getDate() + i);

                let dateName = '';
                if (i === 0) {
                    dateName = '今天';
                } else if (i === 1) {
                    dateName = '明天';
                } else if (i === 2) {
                    dateName = '后天';
                } else {
                    dateName = weekDays[currentDate.getDay()];
                }

                const year = currentDate.getFullYear();
                const month = currentDate.getMonth() + 1;
                const day = currentDate.getDate();
                const dateValue = `${month}月${day}日`;
                const months = String(month).padStart(2, '0')
                const days = String(day).padStart(2, '0')
                const fullDateValue = `${year}-${months}-${days}`
                dateList.push({
                    dateName,
                    dateValue,
                    fullDate: currentDate,
                    fullDateValue: fullDateValue
                });
            }
            this.dateList = dateList;
        }
    }
}
</script>

<style lang="scss">
::v-deep .van-sticky {
    background: #ffffff;

}

/* 样式保持不变 */
:global {

    html,
    body {
        background-color: #F5F6F8 !important;
        margin: 0;
        padding: 0;
        height: 100%;
    }
}

/* 自定义样式 */
.tab-container {
    padding: 10px;
}

.custom-tab {
    min-width: 60px;
    text-align: center;
}

.date-name {
    font-size: 14px;
    margin-bottom: 4px;
    color: #1d2129;
    font-weight: 500;
}

.date-value {
    font-size: 12px;
    color: #86909c;
    position: relative;
}

/* 选中状态样式 */
.van-tab--active .date-name,
.van-tab--active .date-value {
    color: #f53f3f;
}

/* 恢复红色选中线 */
.van-tabs__line {
    background-color: #f53f3f !important;
    height: 2px !important;
    bottom: 0 !important;
}

/* 调整tab容器的padding */
.van-tabs__wrap {
    padding-bottom: 2px;
}

/* 保留原有的自定义下划线（可选） */
.van-tab--active .date-value::after {
    content: '';
    position: absolute;
    bottom: -4px;
    left: 50%;
    transform: translateX(-50%);
    width: 35px;
    height: 335px;
    height: 3px;
    background-color: #f53f3f;
    border-radius: 1px;
}

.head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 15px;
    }

    .title {
        width: 100%;
        text-align: center;
        font-size: 16px;
        color: #000000;
    }
}

//.headers{
//     width: 375px;
//  height: 64px;
//   background: linear-gradient(94deg, rgba(238, 71, 59, 0.05) 0%, #f6766d 58%, rgba(238, 71, 59, 0.3) 100%);
//    opacity: 0.38;
//}
//.headers {
//  width: 375px;
//  height: 64px;
//  line-height: 64px;
//  //margin-left: 12px;
//  padding-left: 15px;
//  box-sizing: border-box;
//  background:
//    /* 左上角 - 高亮白色（0.9透明度） */
//    radial-gradient(ellipse at left top,
//      rgba(255, 255, 255, 0.9) 0%,
//      rgba(255, 255, 255, 0) 30%),
//
//      /* 右上角 - 高亮白色（对称左上角） */
//    radial-gradient(ellipse at right top,
//      rgba(255, 255, 255, 0.9) 0%,
//      rgba(255, 255, 255, 0) 30%),
//
//      /* 主色调线性渐变（顶部最深→底部极淡） */
//    linear-gradient(180deg,
//      rgba(238, 71, 59, 0.95) 0%,
//      /* 最顶部最深（接近实色） */
//      rgba(238, 71, 59, 0.85) 15%,
//      /* 快速过渡保留深色区域 */
//      rgba(238, 71, 59, 0.6) 30%,
//      rgba(238, 71, 59, 0.3) 50%,
//      rgba(238, 71, 59, 0.15) 70%,
//      rgba(255, 255, 255, 0.05) 100%),
//      /* 底部接近透明白 */
//
//      /* 中心径向渐变（顶部最深，中心稍淡） */
//    radial-gradient(ellipse at center,
//      rgba(238, 71, 59, 0.8) 0%,
//      /* 中心点红色（比顶部稍淡） */
//      rgba(238, 71, 59, 0.5) 40%,
//      rgba(255, 255, 255, 0) 80%);
//  background: linear-gradient(94deg, rgba(238, 71, 59, 0.05) 0%, #f6766d 58%, rgba(238, 71, 59, 0.3) 100%);
//  opacity: 0.38;
//}
.film_top {
    padding: 10px 16px;


    .cinema_name {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 20px;
        color: #1A1A1A;
    }

    .address {
        font-family: PingFang SC;
        font-size: 12px;
        width: 100%;
        color: #575757;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
    }
}

.film-info-container {
    position: relative;
}

.select_film_info {
    position: relative;
    background: #fff;
    border-radius: 8px;
    padding: 0 10px;
    // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-top: 10px;

    // &::before {
    //     content: '';
    //     position: absolute;
    //     top: -10px;
    //     left: 50%;
    //     transform: translateX(-50%);
    //     width: 0;
    //     height: 0;
    //     border-left: 10px solid transparent;
    //     border-right: 10px solid transparent;
    //     border-bottom: 10px solid #fff;
    //     z-index: 2;
    // }

    // &::after {
    //     content: '';
    //     position: absolute;
    //     top: -11px;
    //     left: 50%;
    //     transform: translateX(-50%);
    //     width: 0;
    //     height: 0;
    //     border-left: 11px solid transparent;
    //     border-right: 11px solid transparent;
    //     border-bottom: 11px solid rgba(0, 0, 0, 0.1);
    //     z-index: 1;
    // }
}

.film_info_top {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;

    .film_name {
        margin-right: 5px;
        height: 20px;
        line-height: 20px;
        font-family: PingFang SC;
        font-weight: 600;
        font-size: 14px;
        color: #1A1A1A;
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
    }

    .score {
        color: orange;
        font-size: 12px;
    }
}

.film_info_bottom {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    div {
        font-size: 14px;
        color: #999;
        padding: 0 5px;
    }

    .type {
        border-left: 1px solid #999;
        border-right: 1px solid #999;
    }
}


.film_Container {
    display: flex;
    align-items: center;
    overflow-x: auto;
    scroll-behavior: smooth;
    padding: 0 calc(50% - 60px);
    position: relative;
    height: 180px;
    z-index: 1;
    /* 关键：预留给居中的padding */
    gap: 20px;
    scrollbar-width: none;

    &::-webkit-scrollbar {
        display: none;
    }

    .swipe-container {
        flex-shrink: 0;
        scroll-snap-align: center;
        transition: all 0.3s ease;

        &.active .poster {
            height: 145px;
            border: 2px solid white;
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
        }
    }

    .poster {
        width: 100px;
        height: 135px;
        object-fit: cover;
        border-radius: 4px;
    }
}

.film_Container-wrapper {
    position: relative;
    /* 为模糊背景提供定位上下文 */
    width: 100%;
    overflow: hidden;

    .blur-bg {
        position: absolute;
        top: 0px;
        left: 0;
        right: 0;
        line-height: 180px;
        height: 180px;
        /* 模糊区域高度 */
        background-size: cover;
        background-position: center;
        filter: blur(10px) brightness(0.6);
        opacity: 0.7;
        z-index: 0;
        /* 确保在内容层下方 */

        /* 顶部渐变遮罩 */
        // mask-image: linear-gradient(to top, rgba(0,0,0,0.8) 0%, transparent 100%);
        // -webkit-mask-image: linear-gradient(to top, rgba(0,0,0,0.8) 0%, transparent 100%);
    }
}

.movieContent {
    margin-top: 5px;

    .timeDatas {
        display: flex;
        justify-content: space-between;
        padding: 0 9px;
        margin-top: 4px;

        >div:first-child {
            width: 40px;
            flex-shrink: 0;
        }

        .middle-content {
            /* 中间内容 */
            flex: 1;
            min-width: 0;
            /* 关键：允许内容收缩 */
            padding: 0 8px;

            .text-ellipsis {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        >div:nth-child(3) {
            width: 75px;
            color: #EE473B;
            font-size: 14px;
        }

        >div:nth-child(4) {
            width: 50px;
            text-align: center;
            height: 25px;
            line-height: 25px;
            border-radius: 40px;
            border: 1px solid #EE473B;
            color: #EE473B;
        }
    }
}
</style>
